/*
 * Copyright (C) 2020 唐家林
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package controller

import (
	"encoding/json"
	"fmt"
	"github.com/gorilla/mux"
	"github.com/sudot/yapi-tools/internal/db"
	"net/http"
	"strconv"
)

func InterfacesHandler(w http.ResponseWriter, r *http.Request) {
	interfaces, err := db.NewInterfaceDao().FindAll()
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		_, _ = fmt.Fprint(w, err.Error())
	} else {
		_ = json.NewEncoder(w).Encode(interfaces)
	}
}

func InterfaceHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	id, err := strconv.ParseInt(vars["id"], 10, 64)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		_, _ = fmt.Fprint(w, err.Error())
		return
	}
	data, err := db.NewInterfaceDao().FindById(id)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		_, _ = fmt.Fprint(w, err.Error())
	} else {
		_ = json.NewEncoder(w).Encode(data)
	}
}

func InterfaceSaveHandler(w http.ResponseWriter, r *http.Request) {
	data := &db.Interface{}
	_ = json.NewDecoder(r.Body).Decode(data)
	_ = db.NewInterfaceDao().Save(data)
	_ = json.NewEncoder(w).Encode(data)
}

func InterfaceDeleteHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	id, err := strconv.ParseInt(vars["id"], 10, 64)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		_, _ = fmt.Fprint(w, err.Error())
		return
	}
	db.NewInterfaceDao().Delete(id)
}
